﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Expressions;

namespace System
{
    /// <summary>
    /// Summary description for LinqExtension
    /// </summary>
    public static class LinqExtension
    {
        #region Custom OrderBy Property Method
        public static List<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string orderBy, bool orderByDesc) where TEntity : class
        {

            string orderByCommand = orderByDesc ? "OrderByDescending" : "OrderBy";

            var type = typeof(TEntity);
            //Order By
            var orderByProperty = type.GetProperty(orderBy);
            var orderByParameter = Expression.Parameter(type, "ob");
            var orderByPropertyAccess = Expression.MakeMemberAccess(orderByParameter, orderByProperty);
            var orderByExpression = Expression.Lambda(orderByPropertyAccess, orderByParameter);
            Expression queryExpr = source.Expression;
            queryExpr = Expression.Call(typeof(Queryable), orderByCommand, new Type[] { type, orderByProperty.PropertyType }, queryExpr, Expression.Quote(orderByExpression));

            return source.Provider.CreateQuery<TEntity>(queryExpr).ToList();

        }
        #endregion

        public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property)
        {
            return ApplyOrder<T>(source, property, "OrderBy");
        }
        public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string property)
        {
            return ApplyOrder<T>(source, property, "OrderByDescending");
        }
        public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string property)
        {
            return ApplyOrder<T>(source, property, "ThenBy");
        }
        public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string property)
        {
            return ApplyOrder<T>(source, property, "ThenByDescending");
        }
        static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName)
        {
            string[] props = property.Split('.');
            Type type = typeof(T);
            System.Linq.Expressions.ParameterExpression arg = System.Linq.Expressions.Expression.Parameter(type, "x");
            System.Linq.Expressions.Expression expr = arg;
            foreach (string prop in props)
            {
                // use reflection (not ComponentModel) to mirror LINQ
                System.Reflection.PropertyInfo pi = type.GetProperty(prop);
                expr = System.Linq.Expressions.Expression.Property(expr, pi);
                type = pi.PropertyType;
            }
            Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
            System.Linq.Expressions.LambdaExpression lambda = System.Linq.Expressions.Expression.Lambda(delegateType, expr, arg);

            object result = typeof(Queryable).GetMethods().Single(
                    method => method.Name == methodName
                            && method.IsGenericMethodDefinition
                            && method.GetGenericArguments().Length == 2
                            && method.GetParameters().Length == 2)
                    .MakeGenericMethod(typeof(T), type)
                    .Invoke(null, new object[] { source, lambda });
            return (IOrderedQueryable<T>)result;
        }
    }
}